<?php

namespace api\app\controller;

use api\app\model\WalletModel;
use cmf\controller\RestBaseController;
use think\facade\Db;
use think\Request;

class WalletController extends RestBaseController
{
    public function money(Request $request)
    {
        $money = $request->param('money');
        if(!$money)
        {
            $this->error('请输入金额');
        }
        $user = WalletModel::find($request->user_id);
        if(!$user)
        {
            $this->error('参数错误');
        }
        $after = $user['wallet'] + $money;
        // 启动事务
        Db::startTrans();
        try {
            $res = money_log($request->user_id,$money,$user['wallet'],$after,'1');
            $log = WalletModel::where('id','=',$request->user_id)->update(['wallet'=>$after]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        if ($res && $log) {
            // 提交事务
            Db::commit();
            $this->success('充值成功');
        } else {
            // 回滚事务
            Db::rollback();
            $this->error('充值失败');
        }
    }
}